﻿using Microsoft.Extensions.Caching.Memory;
using Newtonsoft.Json;
using System.Net;
using System.Text;
using ZenSystemService.Api.Common.Auth;
using ZenSystemService.Api.DTOs;
using ZenSystemService.Api.Services;
using ZenSystemService.Api.Entities;
namespace ZenSystemService.Api.Business
{
    public class AppletsInterfaceBusiness 
    {
        
        private readonly TencentAccessTokenService _tencentAccessTokenService;

        public AppletsInterfaceBusiness(TencentAccessTokenService tencentAccessTokenService)
        {
            _tencentAccessTokenService = tencentAccessTokenService;
        }
        
        private object _lockGlobal = new object();
        public AccessToken GetAccessCacheToken(string appletSymbol)
        {
            TencentAccessToken LastTencentAccessToken = null;
            var list = _tencentAccessTokenService.GetAllAccessToken(appletSymbol);
            List<TencentAccessToken> TencentAccessTokenList= list.ToList();
            TencentAccessToken TencentAccessTokenEntity = null;
            if (TencentAccessTokenList != null && TencentAccessTokenList.Count > 0)
            {
                TencentAccessTokenEntity = TencentAccessTokenList[0];
            }
            if (TencentAccessTokenEntity == null || TencentAccessTokenEntity.CreateTime.AddSeconds(7100) < DateTime.Now)
            {
                lock (_lockGlobal)
                {
                    AccessToken _accessTocken = GetAccessToken(appletSymbol);
                    if (_accessTocken != null && _accessTocken.errcode == 0)
                    {
                        TencentAccessToken _tencentAccessToken = new TencentAccessToken();
                        _tencentAccessToken.AccessToken = _accessTocken.access_token;
                        _tencentAccessToken.ErrorMsg = _accessTocken.errmsg == null ? "" : _accessTocken.errmsg;
                        _tencentAccessToken.ErrorCode = _accessTocken.errcode;
                        _tencentAccessToken.ExpiresIn = _accessTocken.expires_in;
                        _tencentAccessToken.CreateTime = DateTime.Now;
                        _tencentAccessToken.AppletSymbol = appletSymbol;
                        if (!_tencentAccessTokenService.AddTencentAccessToken(_tencentAccessToken))
                        {
                            return null;
                        }
                        else
                        {
                            LastTencentAccessToken = _tencentAccessToken;
                        }
                    }
                }
            }
            else
            {
                LastTencentAccessToken = TencentAccessTokenEntity;
            }
            if (LastTencentAccessToken == null)
                return null;
            AccessToken returnAccessToken = new AccessToken();
            returnAccessToken.access_token = LastTencentAccessToken.AccessToken;
            returnAccessToken.expires_in = LastTencentAccessToken.ExpiresIn;
            returnAccessToken.errmsg = LastTencentAccessToken.ErrorMsg;
            returnAccessToken.errcode = LastTencentAccessToken.ErrorCode;
            return returnAccessToken;
        }

        /// <summary>
        /// 获取AccessToken
        /// </summary>
        /// <returns></returns>
        public AccessToken GetAccessToken(string appletSymbol)
        {
            string grant_type = "client_credential";
            string appid = "";
            string secret = "";
            if (appletSymbol == "1")//机构
            {
                appid = "wx0423984b8f45527c";
                secret = "9206c71740c4224995470c0603a7dbba";
            }
            else
            {
                appid = "wx068a776814acfd16";
                secret = "03bc18762573bb83a34023553342d4d4";
            }
            string tokenUrl = string.Format("https://api.weixin.qq.com/cgi-bin/token?grant_type={0}&appid={1}&secret={2}", grant_type, appid, secret);
            var wc = new WebClient();
            var strReturn = wc.DownloadString(tokenUrl);
            //  return strReturn.ToObj<AccessToken>();
            return JsonConvert.DeserializeObject<AccessToken>(strReturn);
        }


        /// <summary>
        /// 用户小程序用户手机号
        /// </summary>
        /// <param name="code"></param>
        /// <param name="msg"></param>
        /// <returns></returns>
        public AppletsUserPhoneReceive GetAppletsUserPhoneInfo(string appletSymbol,string code, out string msg)
        {
            msg = "";
            try
            {
                AccessToken _accessTocken =  GetAccessCacheToken(appletSymbol);
                if (_accessTocken==null||_accessTocken.errcode != 0)
                {
                    msg = "获取access_tocken失败:" + _accessTocken.errmsg;
                    return null;
                }
                
                string access_tocken = _accessTocken.access_token;
               
                AppletsUserPhoneRequest _appletsUserPhoneRequest = new AppletsUserPhoneRequest();
                _appletsUserPhoneRequest.code = code;

                string url = "https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=" + access_tocken;

                HttpWebRequest request = null;
                HttpWebResponse response = null;
                Stream reqStream = null;
                request = (HttpWebRequest)WebRequest.Create(url);
                request.Method = "post";    //设置为post请求
                request.ReadWriteTimeout = 5000;
                request.KeepAlive = false;
                // request.ContentType = "application/x-www-form-urlencoded;charset=utf-8";
                request.ContentType = "application/json";
                byte[] postData = Encoding.UTF8.GetBytes(JsonConvert.SerializeObject(_appletsUserPhoneRequest));
                reqStream = request.GetRequestStream();
                reqStream.Write(postData, 0, postData.Length);
                response = (HttpWebResponse)request.GetResponse();
                Stream ioStream = response.GetResponseStream();
                StreamReader sr = new StreamReader(ioStream, Encoding.UTF8);
                string result = sr.ReadToEnd();
                sr.Close();
                ioStream.Close();
                response.Close();

                AppletsUserPhoneReceive model = JsonConvert.DeserializeObject<AppletsUserPhoneReceive>(result);
                return model;
            }
            catch (Exception ex)
            {
                msg = ex.Message;
                return null;
            }

        }
    }


    
}
